package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tuna.UserOp;

/**
 * Servlet implementation class proceedLogin
 */
public class proceedLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		// Get the credentials and do authentication
		PrintWriter out = response.getWriter();
		
		try {
			String us = request.getParameter("us");
			String pw = request.getParameter("pw");
						
			if (us == null || pw == null || us.isEmpty() || pw.isEmpty()) {
				response.setContentType("text/xml");
				out.print("<message>Error: One of fields is missed</message>");
				return;
			}
			
			UserOp user = new UserOp(us);
			
			// If passed, return the encrypted today's date + user + password + role
			if(user.isUserExist(pw)) {
				Calendar now = Calendar.getInstance();
				
				String role = "";
				
				if(user.isProf()) {
					role = "prof";
				}
				else {
					role = "student";
				}
				
				String day = Integer.toString(now.get(Calendar.DAY_OF_MONTH));
				
				int userId = user.getUserId();
				
				response.setContentType("text/xml");
				out.print("<response>");
				out.print("<message>ok</message>");
				out.print("<userId>" + userId + "</userId>");
				out.print("<day>" + day + "</day>");
				out.print("<us>" + us + "</us>");
				out.print("<role>" + role + "</role>");
				out.print("</response>");
			}
			else {
				response.setContentType("text/xml");
				out.print("<message>Error: User does not exist</message>");
			}
		}
		catch (Exception ex) {
			response.setContentType("text/xml");
			out.print("<message>Error: Exception</message>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}
